package org.activemonitoring.monitors;

import org.activemonitoring.harvesters.Harvester;
import org.activemonitoring.harvesters.MeasureBuilder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;

@Aspect
public class AopMethodMonitor {

    private boolean enable = true;
    @Autowired
    private Harvester harvester;
    private String moduleName;

    public AopMethodMonitor() {
        super();
        // TODO Guess module name
    }

    // Prototype method to use with around advices
    public Object monitorMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        if (isEnable() == false) {
            return joinPoint.proceed();
        }
        MeasureBuilder measure = this.harvester.start(this.moduleName, joinPoint);
        try {
            return joinPoint.proceed();
        } catch (Throwable t) {
            measure.error();
            throw t;
        } finally {
            measure.stop();
        }
    }

    public boolean isEnable() {
        return this.enable;
    }

    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    public void setHarvester(Harvester harvester) {
        this.harvester = harvester;
    }

    public void setModuleName(String moduleName) {
        this.moduleName = moduleName;
    }
}
